package com.bestcem.xm.txtanls.controller;

import com.bestcem.xm.common.core.constant.RegTypes;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.component.security.dto.TokenDTO;
import com.bestcem.xm.txtanls.controller.param.analysis.AnalysisProjectParam;
import com.bestcem.xm.txtanls.controller.param.analysis.ProjectUpdateParam;
import com.bestcem.xm.txtanls.controller.vo.PageResponseVO;
import com.bestcem.xm.txtanls.grpc.service.param.PageParam;
import com.bestcem.xm.txtanls.grpc.service.param.analysis.ListAnalysisProjectParam;
import com.bestcem.xm.txtanls.service.AnalysisProjectService;
import com.bestcem.xm.txtanls.service.TrainModelService;
import com.bestcem.xm.txtanls.service.dto.PageResultDTO;
import com.bestcem.xm.txtanls.service.dto.analysis.AnalysisProjectDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;

import static com.bestcem.xm.common.core.constant.Constants.ONE;

/**
 * 文本分析项目相关接口
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v2.0
 * @date 2021/8/4 11:37
 */
@Api(tags = "文本分析项目")
@RestController
@RequestMapping(value = "/txtanls", produces = MediaType.APPLICATION_JSON_VALUE)
public class AnalysisProjectController {


    @Resource
    private AnalysisProjectService analysisProjectService;

    @Resource
    private TrainModelService trainModelService;

    //@Autowired
    //private PackUtil packUtil;

    /**
     * 查询文本分析项目列表
     *
     * @param page 分页页数
     * @param size 每页大小
     * @return 文本分析项目列表
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/5 18:10
     */
    @ApiOperation(value = "查询文本分析项目列表")
    @GetMapping(value = "/projects/")
    public XmResultJson<PageResponseVO<AnalysisProjectDTO>> listAnalysisProject(@RequestParam(value = "page") Integer page,
                                                                                @RequestParam(value = "rowsPerPage") Integer size,
                                                                                @RequestParam(value = "project_status", required = false) Integer status,
                                                                                @RequestParam(value = "project_name", required = false) String name,
                                                                                HttpServletRequest request) {


        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        TokenDTO tokenDTO = SecurityContextHolder.getToken();
        boolean admin = false;
        if (Objects.nonNull(tokenDTO) && tokenDTO.getSuperRole().equals(ONE)) {
            admin = true;
        }
        if (page < 0) {
            return XmResultJson.fail(5, "页号不能小于0");
        }
        if (size < 0) {
            return XmResultJson.fail(5, "每页大小不能小于0");
        }
        if (size > 100) {
            return XmResultJson.fail(5, "每页大小不能大于100");
        }
        PageParam pageParam = new PageParam(page, size);

        ListAnalysisProjectParam param = new ListAnalysisProjectParam(userId, orgId, admin, name, status, pageParam);

        ServiceResult<PageResultDTO<AnalysisProjectDTO>> result = analysisProjectService.listProject(param);
        if (Objects.isNull(result)) {
            return XmResultJson.fail(5, "文本分析项目列表查询失败");
        }
        if (!result.isSuccess()) {
            return XmResultJson.fail(5, result.getMsg());
        }
        return XmResultJson.success(new PageResponseVO<>(pageParam, result.getData()));
    }

    /**
     * 查询单个文本分析项目详情
     *
     * @param id 项目id
     * @return 文本分析项目详情
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/5 18:10
     */
    @ApiOperation(value = "查询单个文本分析项目详情")
    @GetMapping(value = "/projects/{id}")
    public XmResultJson<AnalysisProjectDTO> getAnalysisProject(@ApiParam(value = "项目id", required = true)
                                                               @PathVariable(value = "id") String id) {
        if (!Pattern.matches(RegTypes.OBJECT_ID, id)) {
            return XmResultJson.fail(5, "项目id格式错误");
        }

        ServiceResult<AnalysisProjectDTO> result = analysisProjectService.getById(id);
        if (Objects.isNull(result)) {
            return XmResultJson.fail(5, "文本分析项目详情查询失败");
        }
        if (!result.isSuccess()) {
            return XmResultJson.fail(5, result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }

    /**
     * 创建文本分析项目
     *
     * @param param 项目创建参数
     * @return 创建的文本分析项目
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/5 18:10
     */
    @ApiOperation(value = "创建文本分析项目")
    @PostMapping(value = "/projects/")

    public XmResultJson<AnalysisProjectDTO> createAnalysisProject(@ApiParam(value = "项目创建参数", required = true)
                                                                  @RequestBody AnalysisProjectParam param,
                                                                  HttpServletRequest request) {


        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();
        /*boolean hasPermission = packUtil.hasTxtanlsCreateProjectPackage(orgId);
        if (!hasPermission) {
            return XmResultJson.fail(4, "租户无套餐权限");
        }*/
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(4, violation.getMessage());
        }
        XmResultJson<AnalysisProjectDTO> errorResult = AnalysisProjectParam.validateParam(param);
        if (Objects.nonNull(errorResult)) {
            return errorResult;
        }


        ServiceResult<AnalysisProjectDTO> result =
                analysisProjectService.createProject(param.getCreateServiceParam(userId, orgId));
        if (Objects.isNull(result)) {
            return XmResultJson.fail(5, "文本分析项目创建失败");
        }
        if (!result.isSuccess()) {
            return XmResultJson.fail(5, result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }

    /**
     * 更新单个文本分析项目
     *
     * @param id    项目id
     * @param param 项目更新参数
     * @return 更新后的文本分析项目
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/5 18:10
     */
    @ApiOperation(value = "更新单个文本分析项目")
    @PutMapping(value = "/projects/{id}")
    public XmResultJson<AnalysisProjectDTO> updateAnalysisProject(@ApiParam(value = "项目id", required = true)
                                                                  @PathVariable(value = "id") String id,
                                                                  @ApiParam(value = "项目更新参数", required = true)
                                                                  @RequestBody ProjectUpdateParam param,
                                                                  HttpServletRequest request) {


        String orgId = SecurityContextHolder.getOrgId();
        String userId = SecurityContextHolder.getUserId();

        /*boolean hasPermission = packUtil.hasTxtanlsManageProjectPackage(orgId);
        if (!hasPermission) {
            return XmResultJson.fail(4, "租户无套餐权限");
        }*/
        if (!Pattern.matches(RegTypes.OBJECT_ID, id)) {
            return XmResultJson.fail(5, "项目id格式错误");
        }
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(4, violation.getMessage());
        }
        XmResultJson<AnalysisProjectDTO> errorResult = ProjectUpdateParam.validateParam(param);
        if (Objects.nonNull(errorResult)) {
            return errorResult;
        }

        ServiceResult<AnalysisProjectDTO> result =
                analysisProjectService.updateProject(param.getUpdateServiceParam(id, userId, orgId));
        if (Objects.isNull(result)) {
            return XmResultJson.fail(5, "文本分析项目更新失败");
        }
        if (!result.isSuccess()) {
            if ("项目不存在".equals(result.getMsg())) {
                return XmResultJson.fail(201, result.getMsg());
            }
            return XmResultJson.fail(5, result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }

    /**
     * 删除单个文本分析项目
     *
     * @param id 项目id
     * @return 删除的项目的id
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/5 18:11
     */
    @ApiOperation(value = "删除单个文本分析项目")
    @DeleteMapping(value = "/projects/{id}")
    public XmResultJson<String> deleteAnalysisProject(@ApiParam(value = "项目id", required = true)
                                                      @PathVariable(value = "id") String id) {
        if (!Pattern.matches(RegTypes.OBJECT_ID, id)) {
            return XmResultJson.fail(5, "项目id格式错误");
        }

        ServiceResult<String> result = analysisProjectService.deleteProject(id);
        if (Objects.isNull(result)) {
            return XmResultJson.fail(5, "文本分析项目删除失败");
        }
        if (!result.isSuccess()) {
            return XmResultJson.fail(5, result.getMsg());
        }
        return XmResultJson.success(result.getData());
    }
}
